package com.esiran.payadmin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.esiran.payadmin.dao.OrderDao;
import com.esiran.payadmin.exception.APIRespException;
import com.esiran.payadmin.model.Order;
import com.esiran.payadmin.service.AliPayService;
import com.esiran.payadmin.service.OrderService;
import com.esiran.payadmin.service.WechatPayService;
import com.esiran.payadmin.util.CalendarUtilEx;
import com.esiran.payadmin.util.ImageIOUtilEx;
import com.esiran.payadmin.util.NumUtilEx;
import com.esiran.payadmin.util.QRCodeUtil;
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements OrderService {
    private final WechatPayService wechatPayService;
    private final AliPayService aliPayService;
    @Autowired
    public OrderServiceImpl(WechatPayService wechatPayService, AliPayService aliPayService) {
        this.wechatPayService = wechatPayService;
        this.aliPayService = aliPayService;
    }

    @Override
    public void create(Order order) {

    }

    @Override
    public void updateState(String num, Long state) throws APIRespException {
        Order order = getOrderByNum(num);
        if (order == null){
            throw new APIRespException("订单不存在",-11);
        }
        order.setState(state);
        order.setUpdateTime(CalendarUtilEx.getNow());
        this.updateById(order);
    }

    @Override
    public Order create4merchant(
            String appId,
            String goodsName,
            Double amount,
            String extraId) throws APIRespException {
        return create4merchant(appId,goodsName,amount,extraId,null);
    }

    @Override
    public Order create4merchant(
            String appId, String goodsName,
            Double amount,String extraId,String notifyUrl
    ) throws APIRespException {
        if(!appId.equals("live777_com")){
            throw new APIRespException("订单创建失败",-1001);
        }
        if (StringUtils.isEmpty(extraId)){
            extraId = null;
        }
        if (extraId != null){
            Order exists = getOrderByMerchExtraNum(1L,extraId);
            if (exists!=null){
                throw new APIRespException("订单创建失败，已存在订单",-1009);
            }
        }
        String num = NumUtilEx.makeRegularNum();
        Order order = new Order();
        order.setNum(num);
        order.setMerchId(1L);
        order.setMerchName("live777.xyz");
        order.setExtraId(extraId);
        order.setMerchNum(null);
        order.setGoodsName(goodsName);
        order.setNotifyUrl(notifyUrl);
        Long fixedAmount = NumUtilEx.fixMoney2long(amount);
        if (fixedAmount == null){
            throw new APIRespException("订单创建失败，金额有误",-10002);
        }
        order.setAmount(fixedAmount);
        this.insert(order);
        return order;
    }

    @Override
    public Order getOrderByNum(String num) throws APIRespException {
        if (StringUtils.isEmpty(num)){
            throw new APIRespException("获取订单数据失败，订单编号有误",-10002);
        }
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.where("num = {0}",num);
        return selectOne(wrapper);
    }

    @Override
    public Order getOrderByMerchExtraNum(Long merchId, String extraNum) {
        if (extraNum == null){
            return null;
        }
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.where("merchId = {0}",merchId)
                .and("extraId = {0}",extraNum);
        return selectOne(wrapper);
    }

    @Override
    public String payOrder(String orderNum, Integer payWay) throws APIRespException {
//        Order order = getOrderByNum(orderNum);
//        if (order == null){
//            throw new APIRespException("订单不存在或已失效",-1003);
//        }
//        if (payWay == null||!(payWay.equals(1)||payWay.equals(2))){
//            throw new APIRespException("支付方式错误",-1003);
//        }
//        Map<String,String> mp = wechatPayService.doPayOrder(order);
//        String codeUrl = mp.get("code_url");
//        updateById(order);
        return null;
    }

    @Override
    public String payOrderByQRCode(String orderNum, Integer payWay) throws APIRespException {
        ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (payWay == null||!(payWay.equals(1)||payWay.equals(2))){
            throw new APIRespException("支付方式错误",-1003);
        }
        String host = null;
        String notifyUrl = null;
        if (ra != null){
            host = ra.getRequest().getServerName();
        }
        if (payWay.equals(1)&&host != null){
            notifyUrl = "http://".concat("pay.esiran.com").concat("/api/callback/alipay");
        }else if (host!=null){
            notifyUrl = "http://".concat("pay.esiran.com").concat("/api/callback/wechat");
        }
        return payOrderByQRCode(orderNum,payWay,notifyUrl);
    }

    @Override
    public String payOrderByQRCode(String orderNum, Integer payWay, String notifyUrl) throws APIRespException {
        Order order = getOrderByNum(orderNum);
        if (order == null){
            throw new APIRespException("订单不存在或已失效",-1003);
        }
        if (payWay == null||!(payWay.equals(1)||payWay.equals(2))){
            throw new APIRespException("支付方式错误",-1003);
        }
        String qrCodeString;
        if (payWay.equals(1)){
            qrCodeString = aliPayService.createQRCodeByOrder(order,notifyUrl);
        }else{
            Map<String,String> mp = wechatPayService.doPayOrder(order,notifyUrl);
            qrCodeString = mp.get("code_url");
        }
        if (qrCodeString == null){
            throw new APIRespException("生成二维码错误",-1003);
        }
        try {
            BufferedImage qrCodeImage = QRCodeUtil.toBufferedImage(qrCodeString,200,200);
            return ImageIOUtilEx.image2base64(qrCodeImage,"png");
        } catch (WriterException | IOException e) {
            throw new APIRespException("生成二维码图像错误",-10002);
        }
    }
}
